package com.qdxwx.common.wechat;

import com.alibaba.fastjson2.JSONObject;
import com.qdxwx.common.utils.HttpUtils;

import jakarta.servlet.http.HttpServletRequest;

/**
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
public class WxLogin {

    public static String getLoginUrl(String appId, String retUrl, String state) {
        return "https://open.weixin.qq.com/connect/qrconnect?appid=" +
                appId +
                "&redirect_uri=" + retUrl +
                "&response_type=" + "code" +
                "&scope=" + "snsapi_login" +
                "&state=" + state;
    }


    public static String getLoginSnsUrl(String appId, String retUrl, String state) {
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                appId +
                "&redirect_uri=" + retUrl +
                "&response_type=" + "code" +
                "&scope=" + "snsapi_userinfo" +
                "&state=" + state +
                "#wechat_redirect";
    }

    public static WxToken getAccessToken(String appId, String appSecret, String code) {
        //拼写微信获取access_token访问地址
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";
        return JSONObject.parseObject(HttpUtils.doGet(url), WxToken.class);
        //获取openid
        //String openId = userMap.get("openid").toString();
        //String accessToken = userMap.get("access_token").toString();
    }

    public static WxUserInfo getUserInfo(WxToken wxToken) {
        if (wxToken.getOpenid() == null || wxToken.getAccess_token() == null) {
            return null;
        }
        String url = "https://api.weixin.qq.com/sns/userinfo";
        url += "?access_token=" + wxToken.getAccess_token();
        url += "&openid=" + wxToken.getOpenid();
        url += "&lang=zh_CN";
        return JSONObject.parseObject(HttpUtils.doGet(url), WxUserInfo.class);
    }

    public static boolean isWxBrowser(HttpServletRequest request) {
        return request.getHeader("User-Agent").toLowerCase().contains("micromessenger");
    }
}
